<template>
  <el-dialog   :close-on-click-modal="false" ref="dlg" :visible="true"
   @close="onclosedlg">
    <el-card class="form">
      <form-schema ref="formSchema" :schema="schema" v-model="model" @change="onchange">
        <el-button type="reset" @click="cancel">取消</el-button>
        <el-button type="primary" @click="submit" >提交</el-button>
      </form-schema>
    </el-card>
    <el-dialog :append-to-body="true" :visible.sync="errorVisible">
      <el-alert
        :closable="false"
        :title="error"
        type="error"
      >
      </el-alert>
    </el-dialog>
  </el-dialog>
</template>
<script>
  import FormSchema from '@/components/FormSchema'
  import { Option } from 'element-ui'
  import { getUser } from '@/utils/auth'
  import SelectDate  from '@/components/SelectDate'
  import AutoComplete from '@/components/AutoComplete'
  import MultiSelectTree from '@/components/MultiSelectTree'
  import linq from 'linq'
  // import eventBus from '@/utils/eventBus'
  FormSchema.setComponent('form', 'el-form', ({ vm }) => {
    // vm is the FormSchema VM
    const labelWidth = '200px'
    const model = vm.data
    const rules = {}
    
    vm.fields.forEach((field) => {
      

      const type = field.schemaType === 'array' && field.type === 'radio'
        ? 'string'
        : field.schemaType
      const required = field.required
      const message = "请输入要求格式的值"
      const pattern = field.pattern
      const trigger = ['radio', 'checkbox', 'select'].includes(field.type)
        ? 'change' : 'blur'
        
      // http://element.eleme.io/#/en-US/component/form#validation
      rules[field.name] = { type, required,pattern, message, trigger }
    })
    // returning the form props
    return { labelWidth, rules, model }
  })
  // http://element.eleme.io/#/en-US/component/form#validation

  FormSchema.setComponent('label', 'el-form-item', ({ field }) => ({
    prop: field.name
  }))
  FormSchema.setComponent('email', 'el-input')
  FormSchema.setComponent('text', 'el-input')
  FormSchema.setComponent('textarea', 'el-input')
  FormSchema.setComponent('checkbox', 'el-checkbox')
  FormSchema.setComponent('switch', 'el-switch')
  FormSchema.setComponent('radio', 'el-radio')
  FormSchema.setComponent('select', 'el-select')
  FormSchema.setComponent('multi-select-tree',MultiSelectTree)
  FormSchema.setComponent('date', SelectDate)
  FormSchema.setComponent('autocomplete',AutoComplete);
  FormSchema.setComponent('divide', 'el-divider')
  FormSchema.setComponent('number', 'el-input-number')
  // You can also use the component object
  FormSchema.setComponent('option', Option)

  // By default `<h1/>` is used to render the form title.
  // To override this, use the `title` type:
  FormSchema.setComponent('title', 'h2')

  // By default `<p/>` is used to render the form title.
  // To override this, use the `description` type:
  FormSchema.setComponent('description', 'small')
  // By default `<div/>` is used to render the message error.
  // To override this, use the `error` type:
  FormSchema.setComponent('error', 'el-alert', ({ vm }) => ({
    type: 'error',
    title: vm.error
  }))
  export default {
    props: [ 'data', 'mode','cate','custom','groupCheck'],
    data: () => {
      return ({
        errorVisible:false,
        schema: {},
        error:'',
        
        model: null,
      })
    },
    watch: {
      // This would be called anytime the value of title changes
      data(newValue, oldValue) {
        this.model = newValue;
        // you can do anything here with the new value or old/previous value
      },
    },
    updated(){
      this.$emit("dlg-created");
    },
    created() {
    
      let custom = this.custom?this.custom:[];
      this.model = this.data;
  

      this.schema = require('@/schema/' + this.cate+".json")
      
      custom.forEach(e=>{
        let pro =  this.schema.properties[e.pro];
        pro[e.key] = e.val;
        this.schema.required.push(e.pro);
      })
            var that =this;
      this.$root.eventHub.$on("changeKcsz",kc=>{
         //
         
         if(that.cate == 'A6教师授课情况表'){
           
           that.$nextTick(_=>{
             
            that.model.XZ_SKNJ= kc.XZ_SKNJ;
            that.model.ZYDM = kc.ZYDM;
            that.model.XZ_KCLX = kc.XZ_KCLX;
            that.model.XZ_KCSX = kc.XZ_KCSX
              that.model.XZ_SKRW = kc.XZ_SKRW
            that.model.ZYDM = kc.ZYDM;
            that.model.ZYMC = kc.ZYMC;
            that.model.ZYFXDM = kc.ZYFXDM;
            that.model.ZYFXMC = kc.ZYFXMC;
            that.model.KCDM = kc.KCDM;
           })
     
         }
         //
       })
    },
    methods: {

      onchange(val,name){
    
        var that =this;
      
        
        // if(this.schema.properties[name].attrs.cate == "班级" || 
        // this.schema.properties[name].attrs.cate == "教师基本情况" ||  
        //  this.schema.properties[name].attrs.cate == "机构设置" ||
        //    this.schema.properties[name].attrs.cate == "开设专业" ||
        //      this.schema.properties[name].attrs.cate == "课程设置"
        // ){
        //   Object.keys(that.schema.properties).forEach(e=>{
        //     if(that.schema.properties[e].attrs.follow == name){
        //       console.log("follow "+e)
        //       var data = that.$root[this.schema.properties[name].attrs.cate];
        //       var vals = linq.from(data).first(e=>e[name] == val);
        //       that.$nextTick(_=>{
        //         var tmp =null;
        //          if(e == "XZ_JSXZ"){
        //             tmp="教师性质"
        //          }
        //          else if(e == "FRDB_GH"){
        //            tmp="GH"
        //          }
        //          else{
        //            tmp = e;
        //          }
        //           that.model[e] = vals[tmp];
        //       })
            
        //     }
        //   })
        // }
        
        that.$parent.onchange(that.model,name, val)
        
         
        
      },
      cancel() {
        
        this.$refs.formSchema.reset();
        this.$emit('update:cancel', false)
      },
      onclosedlg(){
        
        this.$emit('update:cancel', false)
        this.$refs.formSchema.reset();
      },
      groupInputCheck(model){
        if(this.groupCheck){
        this.groupCheck.forEach(item=>{
          var blank =true;
          var full = true;
          for(var index in item.data){
             blank = blank && ( model[item.data[index]] == undefined || model[item.data[index]].trim() =="");
             full = full  && ( model[item.data[index]] !== undefined && model[item.data[index]].trim() !=="")
          }
          if(blank || full)
          {
              return ;
          }else{
              throw item.desc;
          }
          
        })
        }
      },
      submit(e) {

        //console.log(this.model)
         console.log(this.groupCheck)
        this.$refs.formSchema.form().validate( async (valid) => {
          if (valid) {

            try {
              // var check = new Promise((resolve, reject) => eventBus.$emit('check', this.model, resolve, reject));
              // await check;
              console.log(this.model)
              this.groupInputCheck(this.model);
              if (this.mode === 'add') {
                this.$emit('add', this.model)
              }
              if (this.mode === 'update') {
        
                this.$emit('update', this.model)
              }
              
            }catch(err)
            {
              this.error = JSON.stringify(err);
              this.errorVisible = true;
            }
          }
        })

        // this.model contains the valid data according your JSON Schema.
        // You can submit your model to the server here
      }
    },
    components: { FormSchema }
  }
</script>

<style>

</style>
